package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMaper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 业务层代码
 */
@Service
public class CategoryService {

    @Autowired
    private CategoryMaper categoryMaper;

    /**
     * 通过父id查询子分类集合
     * @param id
     * @return
     */
    public List<CategoryDTO> queryCategoryByParentId(Long id) {
        // 查询
        Category record = new Category();
        record.setParentId(id);
        List<Category> list = categoryMaper.select(record);
        // 判空
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 把实体类转成DTO
        List<CategoryDTO> categoryDTOList = BeanHelper.copyWithCollection(list, CategoryDTO.class);
        //返回数据
        return categoryDTOList;
    }

    // 根据分类id集合查询分类
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids) {
        List<Category> categoryList = categoryMaper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(categoryList)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }
}
